package com.rtx.edi.system.usermenu.service.impl;

import java.awt.Menu;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import org.apache.shiro.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.rtx.edi.system.usermenu.service.UserPermissionService;
import com.rtx.exception.RtxWmsException;
import com.rtx.model.dto.response.userpermission.TreeResponse;
import com.rtx.model.emums.EnumDataType;
import com.rtx.model.emums.ExceptionCodeEnum;
import com.rtx.model.po.entity.system.MenuPermission;
import com.rtx.model.po.entity.system.User;
import com.rtx.model.po.entity.system.UserPermission;
import com.rtx.model.po.service.MenuPermissionDAO;
import com.rtx.model.po.service.UserDAO;
import com.rtx.model.po.service.UserPermissionDAO;

import cn.hutool.core.date.DateUtil;

@Service
public class UserPermissionServiceImpl implements UserPermissionService{

	@Autowired
	UserDAO userDAO;

	@Autowired
	MenuPermissionDAO menuPermissionDAO;

	@Autowired
	UserPermissionDAO userPermissionDAO;

	@Override
	public List<User> queryAllUserList(User user) {
		LambdaQueryWrapper<User> qw = Wrappers.lambdaQuery();
		if(StringUtils.hasLength(user.getUsername())) {
			qw.like(User::getUsername, user.getUsername());
		}
		if(StringUtils.hasLength(user.getFullname())) {
			qw.like(User::getFullname, user.getFullname());
		}
		return userDAO.selectUserByQueryCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), qw);
	}

	@Override
	public TreeResponse<MenuPermission> queryPermissionList(UserPermission userPermission) {
		String userId = userPermission.getUserId();
		if (userId == null) {
			throw new RtxWmsException(ExceptionCodeEnum.EXC_000023.getCode());
		}
		TreeResponse<MenuPermission> response = new TreeResponse<>();
		List<MenuPermission> menus = menuPermissionDAO.selectMenuPermissionByQueryCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(),Wrappers.lambdaQuery());
		List<MenuPermission> returnMenus = findTreePid(menus);
		// 1.8l拉姆达表达式删除
		returnMenus.removeIf((Menu) -> Menu.getNodes() == null);

		LambdaQueryWrapper<UserPermission> upqw = Wrappers.lambdaQuery();
		upqw.eq(UserPermission::getUserId, userId);
		List<UserPermission> userPermissionList = userPermissionDAO.selectUserPermissionByQueryCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), upqw);
		List<Integer> checkedList = userPermissionList.stream().map(temp->temp.getPermissionId()).collect(Collectors.toList());
		response.setCheckedList(checkedList);
		response.setTreeList(returnMenus);
		return response;
	}


	private List<MenuPermission> findTreePid(List<MenuPermission> MenuPermissionList) {

		List<MenuPermission> genList = new ArrayList<>();
		List<MenuPermission> childrenList = new ArrayList<>();

		for (MenuPermission tree : MenuPermissionList) {
			if (tree.getParentId() == 0 || tree.getParentId() == null) {
				genList.add(tree);
			} else {
				childrenList.add(tree);
			}
		}

		if (genList.size() > 0) {
			for (MenuPermission tree : genList) {
				dgTree(tree, childrenList);
			}
		}
		return genList;
	}

	private void dgTree(MenuPermission root, List<MenuPermission> rootList) {

		List<MenuPermission> children = new ArrayList<>();
		for (MenuPermission tree : rootList) {
			if (tree.getParentId().equals(root.getId())) {
				children.add(tree);

				// 调用自己
				dgTree(tree, rootList);
			}
		}
		if (children.size() > 0) {
			root.setNodes(children);
		}
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public void saveOrDelete(UserPermission permission) {

		String user_id = permission.getUserId();
		List<Integer> list1 = permission.getCheckedList();
		
		LambdaQueryWrapper<UserPermission> upqw = Wrappers.lambdaQuery();
		upqw.eq(UserPermission::getUserId, user_id);
		List<UserPermission> userPermissionList = userPermissionDAO.selectUserPermissionByQueryCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), upqw);
		List<Integer> list2 = userPermissionList.stream().map(temp->temp.getPermissionId()).collect(Collectors.toList());
		
		// 新的权限集合过滤找出不同的-新增
		List<Integer> list3 = list1.stream().filter(item -> !list2.contains(item)).collect(Collectors.toList());
		if (list3 != null && list3.size() >0) {
			User user = (User) SecurityUtils.getSubject().getSession().getAttribute(EnumDataType.USER.getValue());
			for (int permission_id : list3) {
				UserPermission userPermission = new UserPermission();
				userPermission.setPermissionId(permission_id);
				userPermission.setUserId(user_id);
				userPermission.setInsUser(user.getUsername());
				userPermission.setInsTime(DateUtil.date());
				userPermissionDAO.insert(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), userPermission);
			}
		}
		// 旧的的权限集合过滤找出不同的-删除
		List<Integer> list4 = list2.stream().filter(item -> !list1.contains(item)).collect(Collectors.toList());
		if (list4 != null && list4.size() >0) {
			for (int permission_id : list4) {
				LambdaQueryWrapper<UserPermission> delqw = Wrappers.lambdaQuery();
				delqw.eq(UserPermission::getUserId, user_id);
				delqw.eq(UserPermission::getPermissionId, permission_id);
				userPermissionDAO.deleteByCondition(EnumDataType.DEFAULT_DATASOURCE_KEY.getValue(), delqw);
			}
		}
	}   

}
